<?php

namespace app\admin\service\crontab;

use tmcore\base\BaseService;
use app\common\enum\CrontabEnum;
use app\common\model\crontab\SysCrontab;
use tmcore\services\CronExpressionService;

/**
 * 定时任务服务类
 */
class CrontabService extends BaseService
{

    /**
     * 获取定时任务列表
     * @return array
     */
    public static function getList(): array
    {
        // 搜索条件
        $where = self::getSearchData([]);
        $field = 'id,name,command,params,expression,expression_params as expression_desc,status,status as status_desc,last_time,exe_time,max_time,error';
        // 返回分页数据
        return SysCrontab::page($where, self::getPageData(),$field, ['id' => 'desc'], ['status_desc']);
    }

    /**
     * 添加定时任务
     * @param $params
     * @return bool
     */
    public static function add($params)
    {
        return SysCrontab::add([
            'name' => $params['name'],
            'command' => $params['command'],
            'params' => $params['params'],
            'expression' => (new CronExpressionService)->getCronExpression($params['expression']['type'], $params['expression']),
            'expression_params' => json_encode($params['expression'], true),
            'remark' => $params['remark'],
            'status' => $params['status']
        ]);
    }


    /**
     * 查看定时任务详情
     * @param $params
     * @return array
     */
    public static function detail($params)
    {
        $field = 'id,name,command,params,expression_params,expression_params as expression_desc,status,status as status_desc,last_time,exe_time,max_time,error,remark,create_time';
        $row = SysCrontab::field($field)->findOrEmpty($params['id'])->toArray();
        $row['expression'] = $row['expression_params'];
        unset($row['expression_params']);
        return $row;
    }


    /**
     * 编辑定时任务
     * @param $params
     * @return bool
     */
    public static function edit($params)
    {
        return SysCrontab::edit([
            'name' => $params['name'],
            'command' => $params['command'],
            'params' => $params['params'],
            'expression' => (new CronExpressionService)->getCronExpression($params['expression']['type'], $params['expression']),
            'expression_params' => json_encode($params['expression'], true),
            'remark' => $params['remark'],
            'status' => $params['status']
        ], $params['id']);
    }


    /**
     * 删除定时任务
     * @param $params
     * @return bool
     */
    public static function delete($params)
    {
        return SysCrontab::del($params['id']);
    }


    /**
     * 操作定时任务
     * @param $params
     * @return bool
     */
    public static function operate($params)
    {
        try {
            $crontab = SysCrontab::findOrEmpty($params['id']);
            if ($crontab->isEmpty()) {
                throw new \Exception('定时任务不存在');
            }
            switch ($params['operate']) {
                case 'start';
                    $crontab->status = CrontabEnum::START;
                    break;
                case 'stop':
                    $crontab->status = CrontabEnum::STOP;
                    break;
            }
            $crontab->save();

            return true;
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }


    /**
     * 获取规则执行时间
     * @param $params
     * @return array|string
     */
    public static function expression($params)
    {
        try {
            $cronExpressionService = (new CronExpressionService);
            $expression = $cronExpressionService->getCronExpression($params['type'], $params);
            if ($cronExpressionService->verifyExpression($expression) === false) {
                throw new \Exception('定时任务运行规则错误');
            }
            return $cronExpressionService->getExpressionRunDates($expression, 3);
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }
}